package org.rugby.online.core.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

import org.rugby.online.core.exception.RboException;
import org.rugby.online.core.exception.RboExceptionType;

public abstract class NameUtils {
	
	private static final String FILE_PATH = "./res/names/";
	
	private static final String FILE_LAST_NAME = "lastnames";
	
	private static final String FILE_FIRST_NAME = "firstnames";

	/**
	 * Get the file using locale 
	 * @param fileName the file name
	 * @param locale the locale to use
	 * @return the file name
	 */
	private static File getFileWithLocale(String fileName, Locale locale) {
		String path = FILE_PATH + fileName + "." + locale.getLanguage() + ".txt";
		return new File(path);
	}

	
	/**
	 * Get a random last name from locale
	 * @param locale the locale to use
	 * @return the last name
	 * @throws RboException 
	 */
	public static String getRandomFirstName(Locale locale) throws RboException {
		File inputFile = getFileWithLocale(FILE_FIRST_NAME, locale);
		return getRandomLineFrom(inputFile);
	}

	/**
	 * Get a random last name from locale
	 * @param locale the locale to use
	 * @return the last name
	 * @throws RboException 
	 */
	public static String getRandomLastName(Locale locale) throws RboException {
		File inputFile = getFileWithLocale(FILE_LAST_NAME, locale);
		return getRandomLineFrom(inputFile);
	}
	
	/**
	 * Read a random line from a file
	 * @param inputFile the input file to read
	 * @return the line
	 * @throws RboException if file reading problems occurs
	 */
	private static String getRandomLineFrom(File inputFile) throws RboException {
		
		// Init lines
		List<String> lines = new ArrayList<String>();
		
		if (inputFile.isFile() && inputFile.canRead()) {
			try {
				FileReader reader = new FileReader(inputFile);
				BufferedReader bfr = new BufferedReader(reader);
				String line = null;
				while ((line = bfr.readLine()) != null) {
					lines.add(line);
				}
			} catch (FileNotFoundException e) {
				throw new RboException(RboExceptionType.ERROR, "file not found", e);
			} catch (IOException e) {
				throw new RboException(RboExceptionType.ERROR, "streaming error", e);
			}
		} 
		else {
			throw new RboException(RboExceptionType.ERROR, "file for first name not accessible.");
		}
		
		// Check that lines has been found
		if (lines.size() > 0) {
			return lines.get(new Random(UUID.randomUUID().getLeastSignificantBits()).nextInt(lines.size()));
		} else {
			throw new RboException(RboExceptionType.WARNING, "no name found");
		}
	}
	
	
}
